#include <stdio.h>
#include <string.h>

#define BUFSIZE 128

int mycpy(FILE *rfp, FILE *wfp);

// 每次读写一行 fgets(3) fputs(3)
int mycpy_line(FILE *rfp, FILE *wfp);

// 结构化读写 fread(3) fwrite(3)
int mycpy_struct(FILE *rfp, FILE *wfp);

void string_to_lower(char *buf);

void str_transform_to_file(FILE *rfp, FILE *wfp);

int main(int argc, char **argv)
{
    FILE *fp1 = NULL, *fp2 = NULL;

    // argv[1]文件复制到argv[2]
    if (argc < 3)
        return 1;

    fp1 = fopen(argv[1], "r");
    if (NULL == fp1) {
        fprintf(stderr, "fopen():%s failed", argv[1]);
        return 1;
    }

    fp2 = fopen(argv[2], "w");
    if (NULL == fp2) {
        fclose(fp1);
        fprintf(stderr, "fopen():%s failed", argv[2]);
        return 1;
    }

    // mycpy(fp1, fp2);
    // mycpy_line(fp1, fp2);
    // mycpy_struct(fp1, fp2);
    str_transform_to_file(fp1, fp2);

    fclose(fp1);
    fclose(fp2);

    return 0;    
}


int mycpy(FILE *rfp, FILE *wfp)
{
    int c;
    while ((c = fgetc(rfp)) != EOF)
        fputc(c, wfp);

    return 0;
}

// 每次读写一行 fgets(3) fputs(3)
int mycpy_line(FILE *rfp, FILE *wfp)
{
    char buf[BUFSIZE] = {0};

    while (fgets(buf, BUFSIZE, rfp) != NULL) {
        fputs(buf, wfp);
        memset(buf, 0, BUFSIZE); // 清理缓冲区
    }

    return 0;
}

// 结构化读写（二进制读写） fread(3) fwrite(3)
int mycpy_struct(FILE *rfp, FILE *wfp)
{
    char buf[BUFSIZE] = {0};
    int cnt;

    /* fread()不区分文件结束和错误，调用者必须使用 feof(3) 和 ferror(3) 来确定发生了什么。 */
    while ((cnt = fread(buf, 1, BUFSIZE, rfp)) > 0) 
        fwrite(buf, 1, cnt, wfp); // 按照单字节写入，一次写入cnt字节
    
    return 0;
}

void string_to_lower(char *buf)
{
    while (*buf) {
        if (*buf >= 'A' && *buf <= 'Z')
            *buf += 'a' - 'A';
        else if (*buf >= 'a' && *buf <= 'z')
            *buf -= 'a' - 'A';
        buf++;
    }
}

// 将文件内容字符大写转小写，小写转大写，写入到另一个文件中
void str_transform_to_file(FILE *rfp, FILE *wfp)
{
    char buf[BUFSIZE] = {0};

    while (fgets(buf, BUFSIZE, rfp) != NULL) {
        string_to_lower(buf);
        fputs(buf, wfp);
        memset(buf, 0, BUFSIZE);
    }
}

